%% builds the data for figure 2 (cross-correlation conditional on TFP)

% import CSV file
clear;
cd ../nr2020
filename = './NR2020_tfp.csv';
delimiter = ',';
startRow = 2;

formatSpec = '%f%C%C%f%f%f%f%f%f%f%f%f%[^\n\r]';

%% Open the text file.
fileID = fopen(filename,'r');

%% Read columns of data according to the format.
% This call is based on the structure of the file used to generate this
% code. If an error occurs, try regenerating the code
% from the Import Tool in matlab
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'TextType', 'string', 'HeaderLines' ,startRow-1, 'ReturnOnError', false, 'EndOfLine', '\r\n');

%% Close the text file.
fclose(fileID);

%% Allocate imported array to column variable names
markup1 = dataArray{:, 2};
shock = dataArray{:, 3};
step = dataArray{:, 4};
markup = dataArray{:, 5};
lgdp = dataArray{:, 9};

%% Clear temporary variables
clearvars filename delimiter startRow formatSpec fileID dataArray ans;

%% Save irfs
markups = zeros(41,11);
gdps    = zeros(41,11);
steps   = zeros(41,11);
n = 1;

for i = 1:11
    label(i)     = markup1(n);
    markups(:,i) = markup(n:n+40);
    gdps(:,i)    = lgdp(n:n+40);
    steps(:,i)   = step(n:n+40);
    n=n+41;
end
%% simulations 
rng(0);
N  = 10000;
us = randn(N+41,1);

for n = 1:N 
    shocks = us(n:n+40);
    sim_ms(n,:) = shocks'*markups;
    sim_gs(n,:) = shocks'*gdps;
end

%% cross-correlations
corrs = zeros(17,11);
for i = 1:11
    m = sim_ms(:,i);
    g = sim_gs(:,i);
    for j = -8:1:8
            corrs(j+9,i) = corr(m(9+j:9992+j),g(9:9992));
    end
end

cd ../mat_files
save('nr2020_tfp_corrs.mat','corrs','label');
cd ../m_files